#encoding=utf8
import datetime
from django.contrib.auth import *
from django.contrib.auth.models import *
from django.db.models.query_utils import Q
from django.http import *
from django.shortcuts import *
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Count

from trp.models import *
from utils.decorators import *
from utils.utils import date_range_array, date_region_intersect, OrgType
from utils.JsonResponse import JsonResponse, JsonResponseBadrequest
from utils.report import *
from django.db.models import Min,Max,Sum 
import json
from django.template.defaultfilters import floatformat

@login_required
def main(request):
    account=request.user.account
    if account.is_vendor_user() or account.is_merchant_user():
        return render_to_response('trp/cost.html', {'user' : request.user, 'page' : 'cost'})
    else:
        return JsonResponseBadrequest({"message":str("权限不足")})

@login_required
def get_cost_list(request):
    account=request.user.account    
    if not account.is_vendor_user() and not account.is_merchant_user():
        return JsonResponseBadrequest({"message":str("权限不足")})
    
    param = json.loads(request.body)
    pageNo = int(param.get('pageNo',1))
    pageSize =int(param.get("pageSize",20))
    
    org = account.get_organization()
    results = {}
    datalist=[]
    result_count=get_cost_count(org.id)
    total_count=int(result_count["total_count"])  
    range_count=pageSize
    if total_count>0:
        early_date=result_count["start"]
        latest_date=result_count["end"]
        day_num1=(pageNo-1)*pageSize
        day_num2=day_num1+pageSize-1
        end_date=latest_date-datetime.timedelta(days=day_num1)
        start_date=end_date-datetime.timedelta(days=day_num2)
        end_date=datetime.datetime(end_date.year,end_date.month,end_date.day,23,59,59)
        qset1 = DailyOrganizationMediaTypeReport.objects.filter(organization=org,date__range=(start_date,end_date)).order_by('-date','type').annotate(dcount=Count('organization'))
        qset2 = CostLog.objects.filter(time__range=(start_date,end_date),organization=org,deleted=False)
        if total_count/pageSize==(pageNo-1):
            range_count=total_count%pageSize
        for day in range(0,range_count):
            data={}
            date=end_date-datetime.timedelta(days=day)       
            start=datetime.datetime(date.year,date.month,date.day)
            end=datetime.datetime(date.year,date.month,date.day,23,59,59)    
            reports=qset1.filter(date__range=(start,end))
            costlogs=qset2.filter(time__range=(start,end)).values("type").annotate(total_balance=Sum("balance"))
            data["date"]=date.strftime("%Y-%m-%d")
            data["in_cost"]=0
            data["out_cost"]=0
            data["ally_cost"]=0
            if reports:
                for report in reports:
                    if report.type==0:
                        data["in_cost"]+=report.cost
                    elif report.type==1:
                        data["out_cost"]+=report.cost
                    else:
                        data["ally_cost"]+=report.cost
            if costlogs:
                for costlog in costlogs:
                    type=int(costlog.get("type"))
                    cost=float(costlog.get("total_balance"))
                    if type==0:
                        data["in_cost"]+=cost
                    elif type==1:
                        data["out_cost"]+=cost
                    else:
                        data["ally_cost"]+=cost
            datalist.append(data)
    results["bodyData"]=datalist
    results["pageSize"] = pageSize
    results["pageNo"] = pageNo
    results["totalCount"] = total_count       
    return JsonResponse(results)

#获取指定时间当天的站内/站外/联盟花费
def get_cost_log(date,org):
    result={}
    result[0]=0
    result[1]=0
    result[2]=0
    start=datetime.datetime(date.year,date.month,date.day)
    end=datetime.datetime(date.year,date.month,date.day,23,59,59)    
    objs=CostLog.objects.filter(time__range=(start,end),organization=org,deleted=False).values("type").annotate(total_balance=Sum('balance'))
    for obj in objs:
        type=int(obj.get("type"))
        result[type]=obj.get("total_balance")        
    return result

@login_required
def get_record_list(request):
    param = json.loads(request.body)
    pageNo = param.get('pageNo',1)
    pageSize = param.get("pageSize",20)  
   
    org = request.user.account.get_organization()
    if org is None:
        return JsonResponseBadrequest({'message': 'no organization found'})

    qset = PayLog.objects.filter(organization=org).order_by('-time')

    paginator = Paginator(qset, pageSize)

    try:
        reports = paginator.page(pageNo)
    except PageNotAnInteger:
        reports = paginator.page(1)
    except EmptyPage:
        reports = paginator.page(paginator.num_pages)

    results = {}
    results["bodyData"] = []
    results["pageSize"] = pageSize
    results["pageNo"] = pageNo
    results["totalCount"] = paginator.count

    for report in reports:
        results["bodyData"].append({
            'time': report.time.strftime("%Y-%m-%d %H:%M:%S"),
            'in_balance': report.in_balance,
            'out_balance': report.out_balance,
            'ally_balance': report.ally_balance,
        });

    return JsonResponse(results)

@login_required
def get_current_data(request):
    org = request.user.account.get_organization()
    if org is None:
        return JsonResponseBadrequest({'message': 'no organization found'})   
    org_ids=[]
    org_ids.append(org.id)
    datalist=get_current_balance(org_ids,True)
    if not datalist:
        return JsonResponseBadrequest({'message': 'no organization cost found'})
       
    data=datalist[0]
    in_balance=data["in_balance"]  
    out_balance=data["out_balance"]
    ally_balance=data["ally_balance"]
    todayInCost=data["in_cost"]
    todayOutCost=data["out_cost"]
    todayAllyCost=data["ally_cost"]   

    return JsonResponse({'in_balance': in_balance,'out_balance': out_balance,'ally_balance': ally_balance, 'in_cost': todayInCost, 'out_cost': todayOutCost, 'ally_cost': todayAllyCost})

def get_current_balance(org_ids,today_tag):   
    datalist=[]
    try:
        if org_ids:
            real_time_costs={}
            reports=get_organization_report(org_ids)
            organizationCosts=reports["organizationCosts"]
            for organizationCost in organizationCosts:
                org_id=int(organizationCost["id"])
                real_time_costs[org_id]=organizationCost
            orgs=Organization.objects.filter(id__in=org_ids,deleted=False)
            cost_logs=CostLog.objects.filter(organization_id__in=org_ids,deleted=False)
            for org in orgs:
                data={}
                org_id=org.id
                in_balance = org.in_balance
                out_balance = org.out_balance
                ally_balance = org.ally_balance
                objs=cost_logs.filter(organization_id=org_id).values("type").annotate(total_balance=Sum('balance'))
                in_resource_cost=0
                out_resource_cost=0
                ally_resource_cost=0
                for obj in objs:
                    type=int(obj.get("type"))
                    if type==0:
                        in_resource_cost=float(obj.get("total_balance"))
                    elif type==1:
                        out_resource_cost=float(obj.get("total_balance"))
                    else:
                        ally_resource_cost=float(obj.get("total_balance"))
                organizationCost=real_time_costs[org_id]
                in_total_cost=organizationCost.get("total_in")
                out_total_cost=organizationCost.get("total_out")
                ally_total_cost=organizationCost.get("total_ally")
                if today_tag:
                    now=datetime.datetime.now()
                    cost_log=get_cost_log(now,org)
                    in_today_cost=organizationCost.get("today_in")+cost_log[0]
                    out_today_cost=organizationCost.get("today_out")+cost_log[1]
                    ally_today_cost=organizationCost.get("today_ally")+cost_log[2]
                    data["in_cost"]=floatformat(in_today_cost,arg=-2)
                    data["out_cost"]=floatformat(out_today_cost,arg=-2)
                    data["ally_cost"]=floatformat(ally_today_cost,arg=-2)
               
                data["id"]=org_id
                data["name"]=org.name
                data["contact"]=org.contact
                data["description"] = org.description
                data["type"]=org.type
                data["in_balance"]=floatformat(in_balance-in_resource_cost-in_total_cost,arg=-2)
                data["out_balance"]=floatformat(out_balance-out_resource_cost-out_total_cost,arg=-2)
                data["ally_balance"]=floatformat(ally_balance-ally_resource_cost-ally_total_cost,arg=-2)
                datalist.append(data)
    except Exception,e:
        return datalist
    return datalist
                


def get_cost_count(org_id):
    result={}
    count=0
    start1=None
    start2=None
    end1=None
    end2=None
    start=None
    end=None
    today=datetime.datetime.now()
    today_start=datetime.datetime(today.year,today.month,today.day)
    qset1 = DailyOrganizationMediaTypeReport.objects.filter(organization_id=org_id).aggregate(early_date=Min("date"),latest_date=Max("date"))
    qset2=CostLog.objects.filter(deleted=False,organization_id=org_id,time__lt=today_start).aggregate(early_date=Min("time"),latest_date=Max("time"))
    if qset1:
        start1=qset1.get("early_date")
        end1 = qset1.get("latest_date")
    if qset2:
        start2=qset2.get("early_date")
        end2 = qset2.get("latest_date")
    if start1==None:
        if start2!=None:
            start=start2
            end=end2
    else:
        if start2==None:
            start=start1
            end=end1
        else:
            start=start1
            end=end1
            if start1>start2.date():
                start=start2
            if end2.date()>end1:
                end=end2
    if start:
        start=datetime.datetime(start.year,start.month,start.day)
        end=datetime.datetime(end.year,end.month,end.day)
        count=(end-start).days+1    
    result["total_count"]=count;
    result["start"]=start
    result["end"]=end
    return result


    

